from django.shortcuts import render
import random
from datetime import datetime

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.utils.bootstrap import BootStrapModelForm
from app01.utils.pagination import Pagination

class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        # fields = '__all__'
        exclude = ["oid",'admin']
def order_list(request):
    """订单管理"""
    # 显示订单列表
    queryset = models.Order.objects.all().order_by('-id')
    page_object = Pagination(request,queryset)
    form = OrderModelForm()

    context = {
        'form': form,
        "queryset": page_object.page_queryset,
        'page_string': page_object.html()
    }
    return render(request, 'order_list.html', context)

@csrf_exempt
def order_add(request):
    """新建订单 Ajax请求"""
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 根据当前时间年月日时分秒+随机数字生成订单号，datetime，random
        form.instance.oid = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000,9999))
        # 根据当前登录找好的ID生成管理员
        form.instance.admin_id = request.session["info"]["id"]
        # 保存到数据库中
        form.save()
        # 序列化
        return JsonResponse({'status': True})

    return JsonResponse({'status': False,'error': form.errors})

def order_delete(request):
    """ajax的GET请求删除数据"""
    # 从前端获取到要删除的ID
    uid = request.GET.get('uid')
    # 数据库中找到数据
    exists = models.Order.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, 'error': "删除失败！数据不存在，或已被删除"})
    # 如果有数据，直接删除
    models.Order.objects.get(id=uid).delete()
    return JsonResponse({"status": True})

def order_detail(request):
    """根据订单ID获取订单详细信息，编辑"""
    uid = request.GET.get('uid')
    # row_object获取到的是一个对象
    # row_object = models.Order.objects.filter(id=uid).first()
    # 获取的是一个字典
    row_dict = models.Order.objects.filter(id=uid).values('title','price','status').first()
    if not row_dict:
        return JsonResponse({"status": False, 'error': "删除失败！数据不存在，或已被删除"})
    # 把字典信息封装到result中传递到前端
    result = {
        "status": True,
        "data": row_dict
    }
    return JsonResponse(result)

@csrf_exempt
def order_edit(request):
    """ 编辑订单 """
    uid = request.GET.get('uid')
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status": False, 'tips': "删除失败！数据不存在，或已被删除"})

    form = OrderModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": True, 'error': form.errors})